<?php
/**
 * 图片画册
 * AUTHOR  : zlf
 * DateTime: 2022/06/18 09:00
 */
namespace App\Api\Controllers;
use Illuminate\Http\Request;
use App\Api\Services\TextImageTemplatesService;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Api\BaseController;
use App\Api\Models\TextImageTemplatesModel;
class TextImageTemplatesController extends BaseController
{
   /**
     * 添加模板
     * 
     * @param temp_title        模板标题
     * @param temp_color        模板颜色
     * @param temp_number       模板序号
     * @param temp_content1     模板内容1 
     * @param temp_content2     模板内容2 
     * @param h5_temp_id        H5模板id
     * @param pa_id             文字图片画册id
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2 
     * @param temp_type         模板类型：1、单图/单视频  2、多图/多视频 3、背景模板 4、首页封面模板
     */
     public function addContentTempLate(Request $request){
         
        $data=SELF::handlePostData($request);//处理Post请求的数据包
        
        if ($data['code'] === 0){
        
            $data            = $data['data'];
            $data['user_id'] = $this->getUserId();
            $res=TextImageTemplatesService::addContentTempLate($data);
            
            if($res['code']===0){
                
                $this->log('文字画册内容模板,添加成功', $res);                
            }
                return response()->json($res);
        }else{
            return response()->json($data);
        }
        
    }
       
    /**
     * 删除模板
     * 
     * @param t_id 模板id
     */
    public function delContentTempLate(Request $request){
        
        if(empty($request->input('t_id'))){
        
            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        } 
        
        $condition['user_id'] = $this->getUserId();
        $condition['id']      = $request->input('t_id');

        $info=TextImageTemplatesService::getTextImageTemplatesInfo($condition);
        
        if (empty($info)){
            
            return response()->json(['code'=>1,'msg'=>'请求不合法','data'=>null]);
        }
         //素材01,删除服务器中没有用的素材图片
        if(!empty($info['temp_img_video_01'])){
            
            $info['temp_img_video_01'] = explode(',',$info['temp_img_video_01']);
          
            foreach ($info['temp_img_video_01'] as $ivkey1=>$ivval1){
                
                if(is_file(public_path($ivval1))){
                    
                    unlink(public_path($ivval1));//删除服务器，已上传的图片
                }
            }
        }
        
        //素材02,删除服务器中没有用的素材图片
        if(!empty($info['temp_img_video_02'])){
        
            $info['temp_img_video_02'] = explode(',',$info['temp_img_video_02']);
        
            foreach ($info['temp_img_video_02'] as $ivkey2=>$ivval2){
        
                if(is_file(public_path($ivval2))){
        
                    unlink(public_path($ivval2));//删除服务器，已上传的图片
                }
            }
        }
        
        $bool = TextImageTemplatesService::delContentTempLate($condition);
        
        if($bool){
            
            $this -> log('文字图片画册，删除成功', $bool);
            
            return response()->json(['code'=>0,'msg'=>'删除成功','data'=>null]);
        }
        
            return response()->json(['code'=>1,'msg'=>'删除失败','data'=>null]);
    }
    
    /**
     * 修改模板
     * 
     * @param t_id              模板id
     * @param temp_title        模板标题
     * @param temp_color        模板颜色
     * @param temp_number       模板序号
     * @param temp_content1     模板内容1 
     * @param temp_content2     模板内容2 
     * @param h5_temp_id        H5模板id
     * @param pa_id             文字图片画册id
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2 
     * @param temp_type         模板类型：1、单图/单视频  2、多图/多视频 3、背景模板 4、首页封面模板
     */
    public function updateContentTempLate(Request $request){
        
        if(empty($request->input('t_id'))){
            
            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }
        
        $data = SELF::handlePostData($request);//处理Post请求的数据包
        
        if ($data['code'] === 0){
            
            unset($data['data']['info']);
            $data['data']['user_id'] = $this->getUserId();
            
            $res = TextImageTemplatesService::updateContentTempLate($data['data']);
            
            if($res['code'] === 0){
            
                $this->log('文字图片画册，修改成功', $res);  
            }
            
            return response()->json($res);
        }else{
            return response()->json($data);
        }
    }
    
    /**
     * 更换素材中某个的图片/视频
     * 
     * @param t_id     素材id
     * @param old_path 原图片or视频路径
     * @param temp_img_video_01 模板素材图片/视频 1
     * @param temp_img_video_02 模板素材图片/视频 2
     */
    public function updMaterialImgVideo(Request $request){
        
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            't_id'     =>'required',
            'old_path' =>'required',            
        ],
            [
            't_id.required'    => '缺必要参数，文字画册id',
            'old_path.required'=> '原图片or视频路径，不能为空'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
        
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
             
        //修改时，传递的内容模板id
        if(!empty($data['t_id'])){
        
            $condition['id'] = $data['t_id'];
        
            $info = TextImageTemplatesService::getTextImageTemplatesInfo($condition);
        
            if(!empty($info)){
        
                $data['info'] = $info;
        
            }else{
        
                return ['code' => 1,'msg'  => '内容模板不存在！','data' => ''];
            }
        }
        
            $flag = "temp_img_video_01";
        
        if(!empty($request->file("temp_img_video_02"))){
            
            $flag = "temp_img_video_02";
        }
        $data = SELF::handleUploadTempImageVideo($request, $data, $flag);

            if($data['code']===0){

             $file_path = $data[$data['m_flag']];
                
            return response()->json(['code'=>0,'msg'=>'更换成功','data'=>['new_path'=>$file_path]]);
        
        }else{
        
        
            return response()->json(['code'=>1,'msg'=>$data['msg'],'data'=>null]);
        }
    }
    
    /**
     * 查询模板列表
     * 
     * @param pa_id     文字画册id
     * @param curr_page 页码
     */
    public function getContentTempLateList(Request $request){
        
        if(empty($request->input('pa_id'))){
        
            return response()->json(['code'=>1,'msg'=>'缺必要参数，文字画册id','data'=>null]);
        }
        
        $condition['act.user_id'] = $this->getUserId();
        $condition['act.pa_id']   = $request->input('pa_id');
        
        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
        $pageSize = !empty($request->input('page_size'))?$request->input('page_size'):20;
        $list        = TextImageTemplatesService::getContentTempLateList($condition, $currentPage,$pageSize);
        
        if(!empty($list['data'])){
            
            foreach ($list['data'] as $lk=>$lv){
                
                if (!empty($lv['temp_img_video_01'])){
                    
                    $list['data'][$lk]['temp_img_video_01']=explode(',', $lv['temp_img_video_01']);
                }
                
                if (!empty($lv['temp_img_video_02'])){
                    
                    $list['data'][$lk]['temp_img_video_02']=explode(',', $lv['temp_img_video_02']);
                }
                
                $list['data'][$lk]['create_time']=date('Y-m-d H:i:s', $lv['create_time']);
                $list['data'][$lk]['update_time']=date('Y-m-d H:i:s', $lv['update_time']);
            }
        }
        $this -> log('文字画册内容模板，查询成功', $list);
        
        return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$list]);
    }
    
    /**
     * 查询模板信息
     *
     * @param t_id     内容模板id
     * 
     */
    public function getContentTempLateInfo(Request $request){

        if(empty($request->input('t_id'))){
        
            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }
        
        $condition['user_id'] = $this->getUserId();
        $condition['id']      = $request->input('t_id');
        
        $info = TextImageTemplatesService::getTextImageTemplatesInfo($condition);
        
        if(!empty($info)){
            if(!empty($info['temp_img_video_01'])){
                
            $info['temp_img_video_01'] = explode(',', $info['temp_img_video_01']);
            
            }
            if(!empty($info['temp_img_video_02'])){
                
            $info['temp_img_video_02'] = explode(',', $info['temp_img_video_02']);
            
            }
            
            return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$info]);
            
        }else{
            
            return response()->json(['code'=>1,'msg'=>'查询失败','data'=>null]);
        }
        
    }
    
    /**
     * 删除素材中的图片
     * 
     * @param t_id        素材模板id 
     * @param del_img_paths 删除原图片的路径 
     * @param m_flag      删除原素材字段名
     */
    public function delMaterialImgVideo(Request $request){

        if(empty($request->input('t_id'))){
        
            return response()->json(['code'=>1,'msg'=>'缺必要参数，模板id','data'=>null]);
        }
        
        //参数验证
        $validator = Validator::make($data = $request->all(), [       
            't_id'        =>'required',
            'del_img_paths' =>'required',
            'm_flag'      =>'required'
        ],
            [
                't_id.required'          => '缺必要参数，模板id',
                'del_img_paths.required'   => '图片路径，不能为空',
                'm_flag.required'        => '素材标识，不能为空'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return ['code' => 1,'msg'  => $info,'data' => ''];
        }
        
        $condition['id']      = $data['t_id'];
        $condition['user_id'] = $this->getUserId();
        
        $info=TextImageTemplatesService::getTextImageTemplatesInfo($condition);
        
        if (empty($info)){
        
            return response()->json(['code'=>1,'msg'=>'内容模板不存在！','data'=>null]);
        }
        //删除服务器中没有用的素材图片
        if(!empty($info[$data['m_flag']])){
            
                $paths = "";
            
                $data['del_img_paths'] = explode(',',$data['del_img_paths']);
                $info[$data['m_flag']] = explode(',',$info[$data['m_flag']]);
            
                foreach ($info[$data['m_flag']] as $key=>$val){
                    
                    if(in_array($val,$data['del_img_paths'])){
                        
                        if(is_file(public_path($val))){
                            
                            unlink(public_path($val));
                        }
                        
                    }else{
                        
                      $paths.=$val.',';  
                    }
                }
                $updData[$data['m_flag']] = substr($paths,0,strrpos($paths,","));
            
                $bool = TextImageTemplatesModel::updateContentTempLate($condition,$updData);
            
                if($bool){
            
                    return ['code'=>0,'msg'=>'删除成功','data'=>$bool];
            
                }else{
            
                    return ['code'=>1,'msg'=>'删除失败','data'=>null];
                }
        }
    }
    
    /**
     * 处理Post请求的数据
     */
    static public function handlePostData($request){       
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            
            'pa_id'      =>'required',
            'temp_type'  =>'required',
        ],
        [
            'pa_id.required'       => '缺少参数，文字画册id',
            'temp_type.required'   => '缺少参数，模板类型'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return ['code' => 1,'msg'  => $info,'data' => ''];
        }
        
        $tinfo = [];
        
        //修改时，传递的内容模板id
        if(!empty($data['t_id'])){
            
            $condition['id'] = $data['t_id'];
            
            $tinfo = TextImageTemplatesService::getTextImageTemplatesInfo($condition);
            
            if(!empty($tinfo)){
                
            $data['info'] = $tinfo;
            
            }else{
                
                return ['code' => 1,'msg'  => '内容模板不存在！','data' => ''];
            }
        }
        $temp_info_data1 = SELF::updUploadTempImageVideo($request,$data,'temp_img_video_01');//处理上传素材的图片视频函数
        
        if ($temp_info_data1['code'] === 0){
        
            $data = $temp_info_data1['data'];
        
        }else{
            
            return $temp_info_data1;
        }
        if($data['temp_type'] == 2){//多图/多视频模板
        
            $temp_info_data2 = SELF::updUploadTempImageVideo($request,$data,'temp_img_video_02');//处理上传素材的图片视频函数
        
            if ($temp_info_data2['code'] === 0){
        
                $data = $temp_info_data2['data'];
        
            }else{
                return $temp_info_data2;
            }
        }
      return ['code' => 0,'msg'  => 'success','data' => $data]; 
    }
    
   
    /**
     * 处理上传素材的图片视频函数
     */
    static public function handleUploadTempImageVideo($request,$fdata,$temp_img_video){
        
        $data = [];
        $data[$temp_img_video] = '';
        
        //添加内容模板时，上传素材01、上传素材02
        if(!empty($temp_img_video_files = $request->file($temp_img_video))){
        
            $temp_img_video_str = '';
        
            foreach ($temp_img_video_files as $key=>$vfile){
        
                $key=$key+1;
        
                if($vfile->isValid()){                    
                    $temp_img_video_path = $vfile->store('huace/text/temp/'.$temp_img_video.'/'.date('Y').'-'.date('m').'-'.date('d'));
                    $temp_img_video_path = '/uploads/'.$temp_img_video_path;
                    $temp_img_video_str .=$temp_img_video_path.',';
                }else{
        
                    return ['code' => 1,'msg' => '第'.$key.'图片/视频上传失败','data' => ''];
                }
            }
             
            $data[$temp_img_video] = substr($temp_img_video_str,0,strrpos($temp_img_video_str,","));

        }elseif(!empty($request->input($temp_img_video))){
             
            $data[$temp_img_video] = $request->input($temp_img_video);
        }    
        
        if(!empty($fdata['info'][$temp_img_video])){
            //更换素材时，删除服务器中没有用的素材图片
            if(!empty($fdata['old_path'])){

                if(is_file(public_path($fdata['old_path']))){
                    //删除服务器，已上传素材图片
                    unlink(public_path($fdata['old_path']));
                }
                unset($fdata);
                return ['code' => 0,'msg'  => 'success','data' => $data];
                
            }else{                
            //修改文字画册内容时，删除服务器中没有用的素材图片
            $temp_img_video_arr2 = explode(',', $data[$temp_img_video]);
                       
            $temp_img_video_arr1 = explode(',', $fdata['info'][$temp_img_video]);

            foreach ($temp_img_video_arr1 as $ivkey=>$ivval){
                
                if(!in_array($ivval, $temp_img_video_arr2)){
                    
                    if(is_file(public_path($ivval))){
                    //删除服务器，已上传的图片
                    unlink(public_path($ivval));
                    
                    }
                }
             }
           }
        }
        $fdata = array_merge($fdata,$data);
        return ['code' => 0,'msg'  => 'success','data' => $fdata];
    }

    /**
     * 修改上传素材的图片视频函数
     */
    static public function updUploadTempImageVideo($request,$fdata,$temp_img_video){
    
        $data = [];
        $data[$temp_img_video] = '';
    
        //添加内容模板时，上传素材01、上传素材02
        if(!empty($temp_img_video_files = $request->$temp_img_video)){
    
            $temp_img_video_str = '';
           
            ksort($temp_img_video_files);
            foreach ($temp_img_video_files as $key=>$vfile){
    
                $key=$key+1;

                
                if(is_file($vfile)){
                    $res = SELF::handlePicFormat($vfile,'pv','第 '.$key.' 个格式有误！');//判断文件格式
                     
                    if(!empty($res)){
                         
                        return $res;
                    }
                    if($vfile->isValid()){
                        $temp_img_video_path = $vfile->store('huace/text/temp/'.$temp_img_video.'/'.date('Y').'-'.date('m').'-'.date('d'));
                        $temp_img_video_path = '/uploads/'.$temp_img_video_path;
                        $temp_img_video_str .=$temp_img_video_path.',';
                    }else{
        
                        return ['code' => 1,'msg' => '第'.$key.'图片/视频上传失败','data' => ''];
                    }
                }else{
                    $temp_img_video_str .=$vfile.',';
                }
            }
             
            $data[$temp_img_video] = substr($temp_img_video_str,0,strrpos($temp_img_video_str,","));
    
        }elseif(!empty($request->input($temp_img_video))){
             
            $data[$temp_img_video] = $request->input($temp_img_video);
        }
    
        if(!empty($fdata['info'][$temp_img_video])){
            //更换素材时，删除服务器中没有用的素材图片
            if(!empty($fdata['old_path'])){
    
                if(is_file(public_path($fdata['old_path']))){
                    //删除服务器，已上传素材图片
                    unlink(public_path($fdata['old_path']));
                }
                unset($fdata);
                return ['code' => 0,'msg'  => 'success','data' => $data];
    
            }else{
                //修改文字画册内容时，删除服务器中没有用的素材图片
                $temp_img_video_arr2 = explode(',', $data[$temp_img_video]);
                 
                $temp_img_video_arr1 = explode(',', $fdata['info'][$temp_img_video]);
    
                foreach ($temp_img_video_arr1 as $ivkey=>$ivval){
    
                    if(!in_array($ivval, $temp_img_video_arr2)){
    
                        if(is_file(public_path($ivval))){
                            //删除服务器，已上传的图片
                            unlink(public_path($ivval));
    
                        }
                    }
                }
            }
        }
        $fdata = array_merge($fdata,$data);
        return ['code' => 0,'msg'  => 'success','data' => $fdata];
    }
    
     /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files,$flag,$msg){
 
        $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                            flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                            bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                            ufo,eps,ai,raw,wmf,webp,avif,apng';
        
        $pic_format       = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
        
        $music_format     = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';
        
        $ext = $files->extension();
        $ext = strtolower($ext);
        
        if($flag == 'm'){
        
            $pic_video_format_arr = explode(',',$music_format);
        
        }elseif($flag == 'p'){
            
            $pic_video_format_arr = explode(',',$pic_format);
            
        }else{
            
            $pic_video_format_arr = explode(',',$pic_video_format);
        }
         
        if (!in_array($ext, $pic_video_format_arr)) {
             
            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }
         
    }
}
